package com.maplefire.service;

import com.maplefire.annotation.MessageHandlerType;
import com.maplefire.handler.MessageHandler;
import com.maplefire.service.impl.MessageHandlerTypeImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: maplefire
 * @Description:
 * @Date: 2021/5/18 16:56
 */
@Service
public class MessageService<T> {

    /**
     * 自理解：messageHandlerMap的key是满足operateType固定等于xx和source固定等于yy的一个实现类
     */
    private Map<MessageHandlerType, MessageHandler> messageHandlerMap;

    /**
     * Spring会先实例化所有Bean，然后根据配置进行扫描，当检测到@Autowired后进行注入，注入时调用这个方法
     */
    @Autowired
    public void setMessageHandlerMap(List<MessageHandler> messageHandlers) {
        //注入各种类型的消息处理类
        messageHandlerMap = messageHandlers.stream().collect(Collectors.toMap(
                messageHandler -> AnnotationUtils.findAnnotation(messageHandler.getClass(), MessageHandlerType.class),
                v -> v, (v1, v2) -> v2));
    }

    public void doHandler(String action, String source, T t) {
        MessageHandlerTypeImpl messageHandlerType = new MessageHandlerTypeImpl(action, source);
        MessageHandler messageHandler = messageHandlerMap.get(messageHandlerType);
        if (null != messageHandler) {
            messageHandler.handler(t);
        }
    }
}
